package com.qf.business.hotel.controller;

import com.qf.common.core.base.R;
import com.qf.common.core.base.RetUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

@RestController
@RequestMapping("/file")
@Slf4j
public class FileController {

    private static final String UPLOAD_PATH = "D:\\img";

    /**
     * 文件上传
     * @return
     */
    @RequestMapping("/upload")
    public R upload(MultipartFile file){
        String fileName = UUID.randomUUID().toString();
        File outfile = new File(UPLOAD_PATH, fileName);
        try (
                InputStream in = file.getInputStream();
                FileOutputStream out = new FileOutputStream(outfile);
        ) {
            IOUtils.copy(in, out);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return RetUtils.createSucc(outfile.getAbsolutePath().replace("\\", "/"));
    }

    /**
     * 根据路径获取图片
     * @return
     */
    @RequestMapping("/getImg")
    public void getImg(String path, HttpServletResponse response){
        log.info("[getImg] - 根据路径获取图片 - {}", path);
        try(
                InputStream in = new FileInputStream(path);
                OutputStream out = response.getOutputStream();
        ) {
            IOUtils.copy(in, out);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
